# -*- coding: UTF-8 -*-
"""
无人机
By AnpyD
"""

import bs
import bsUtils
import bsInternal

class Ball(bs.Actor):

    def animate(self):
        bsUtils.animate(self.node, 'modelScale', {0: 0.3, 2000: 0.28, 3000: 0.0})

    def __init__(self, position=(0, 1, 0), velocity=(0, 0, 0), source_player=None):
        bs.Actor.__init__(self)

        self.source_player = source_player

        self.bombMaterial = bs.Material()
        self.bombMaterial.addActions(
            conditions=((('weAreYoungerThan', 100),
                         'or', ('theyAreYoungerThan', 100)),
                        'and', ('theyHaveMaterial',
                                bs.getSharedObject('objectMaterial'))),
            actions=(('modifyNodeCollision', 'collide', False)))

        # we want pickup materials to always hit us even if we're currently not
        # colliding with their node (generally due to the above rule)
        self.bombMaterial.addActions(
            conditions=('theyHaveMaterial',
                        bs.getSharedObject('pickupMaterial')),
            actions=(('modifyPartCollision', 'useNodeCollide', False)))

        self.bombMaterial.addActions(actions=('modifyPartCollision',
                                              'friction', 0.3))

        self.node = bs.newNode('prop', delegate=self, attrs={
            'position': position,
            'velocity': velocity,
            'model': bs.getModel('shield'),
            'body': 'sphere',
            'shadowSize': 0.5,
            'colorTexture': bs.getTexture('black'),
            'reflection': 'sharper',
            'reflectionScale': [1],
            'materials': [self.bombMaterial,
                          bs.getSharedObject('objectMaterial'),
                          bs.getSharedObject('footingMaterial')]})

        bsUtils.animate(self.node, 'modelScale', {0: 0, 200: 0.6, 260: 0.3})
        bs.gameTimer(260, self.animate)

    def handleMessage(self, m):
        if isinstance(m, bs.DieMessage):
            if self.node.exists():
                self.node.delete()
        
        if isinstance(m, bs.HitMessage):
            if self.node.exists() and m.hitType == "explosion":
                bs.Blast(position=self.node.position, blastRadius=2.5, sourcePlayer=self.source_player)
                self.node.delete()

        elif isinstance(m, bs.OutOfBoundsMessage):
            if self.node.exists():
                self.node.delete()



class Drone(object):
    def __init__(self):
        pass

    def GetName(self, name):
        for i in bsInternal._getForegroundHostActivity().players:
            if i.getName() == name:
                return i

    def NodeFP(self, player='None', node=None):
        try:
            p = self.GetName(name=player)
            p.actor.node.handleMessage('celebrate', 10000)
            pos = p.actor.node.position
            if node is None and p.isAlive():
                node = Ball(position=(pos[0],pos[1]+3,pos[2]), source_player=p).autoRetain().node
                bs.gameTimer(3000, bs.Call(p.actor.node.handleMessage, 'celebrate', 0))
                bs.gameTimer(3000, bs.Call(node.delete))
            else:
                node.position = (pos[0],pos[1]+3,pos[2])
                node.extraAcceleration = (0,0,0)
                scale = node.modelScale
            def up():
                try:
                    v = node.velocity
                    node.velocity = (v[0], v[1]+40, v[2])
                except:
                    reset()
            def down():
                try:
                    v = node.velocity
                    node.velocity = (v[0], v[1]-40, v[2])
                except:
                    reset()
            def go():
                try:
                    v = node.velocity
                    node.velocity = (v[0]-40, v[1], v[2])
                except:
                    reset()
            def back():
                try:
                    v = node.velocity
                    node.velocity = (v[0]+40, v[1], v[2])
                except:
                    reset()
            def left():
                try:
                    v = node.velocity
                    node.velocity = (v[0], v[1], v[2]-40)
                except:
                    reset()
            def right():
                try:
                    v = node.velocity
                    node.velocity = (v[0], v[1], v[2]+40)
                except:
                    reset()
            def blast():
                bs.Blast(position=node.position, blastRadius=2.5, sourcePlayer=p)
                reset()
            def reset():
                try:
                    p.actor.connectControlsToPlayer()
                    p.actor.node.handleMessage('celebrate', 0)
                    bs.gameTimer(5,node.delete)
                    bs.animate(node,'modelScale',{0:scale, 500:0})
                except:
                    pass
            p.actor.disconnectControlsFromPlayer()
            p.assignInputCall('pickUpPress', up)
            p.assignInputCall('jumpPress', down)
            p.assignInputCall('leftPress', go)
            p.assignInputCall('rightPress', back)
            p.assignInputCall('upPress', left)
            p.assignInputCall('downPress', right)
            p.assignInputCall('punchPress', reset)
            p.assignInputCall('bombPress', blast)
            m=bs.newNode('math', 
                        owner=node, 
                        attrs={ 'input1':(0, 0.5, 0),
                                 'operation':'add' })
            node.connectAttr('position', m, 'input2')
            text=bs.newNode('text', 
                            owner=node, 
                            attrs={'text':p.getName()+u' 的无人机', 
                            'inWorld':True, 
                            'shadow':1.0, 
                            'flatness':1.0, 
                            'color':p.getTeam().color, 
                            'scale':0.008, 
                            'hAlign':'center'})
            m.connectAttr('output', text, 'position')

        except Exception as e:
            raise ImportError
